package com.clay.appointment.config;

import com.clay.appointment.common.annotation.AuthToken;
import com.clay.appointment.common.exception.ExceptionEnum;
import com.clay.appointment.common.exception.GlobalException;
import com.clay.appointment.utils.RequestContextUtils;
import com.clay.appointment.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 校验token拦截器
 * @author clay
 * @since 2021/7/20
 */
@Configuration
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Value(value = "${token.name}")
    private String tokenName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method.hasMethodAnnotation(AuthToken.class)) {
                return this.authToken();
            }
        }
        return true;
    }

    /**
     * 验证权限
     */
    public boolean authToken() {
        HttpServletRequest request = RequestContextUtils.getRequest();
        String token = null;

        try {
            token = request.getHeader(tokenName);
            if (!TokenUtils.verify(token)) {
                GlobalException.throwOut();
            }
            return true;
        } catch (Exception e) {
            log.error("鉴权失败，token=" + token);
            GlobalException.throwOut(ExceptionEnum.AUTH_FAILED);
            return false;
        }
    }
}